import React, {useEffect, useRef} from 'react';
import {
    Button,
    Card,
    Form,
    Input,
    Modal,
    Radio,
    Select,
    Space,
    Switch,
    Table, message, Upload, Avatar, Tooltip
} from 'antd';
import {useState} from 'react';
import {
    DeleteOutlined,
    EditOutlined,
    DownloadOutlined,
    LoadingOutlined,
    PlusOutlined,
} from "@ant-design/icons";
import {
    reqAddUserList, reqDeleteUser,
    reqDeleteUserList,
    reqGetUserList, reqUpdateUser
} from "../../../../api/backStage/backStageApi";
import classes from './index.module.scss'
import axios from "axios";
import {exportExcel} from 'xlsx-oc'
import {debounce} from "lodash";


//展开的默认内容
const defaultExpandable = {
    expandedRowRender: (record) => (
        record.user_signature ? <p style={{margin: 0, color: '#999'}}>{record.user_signature} </p> :
            <p style={{color: 'red'}}>暂无签名</p>
    ),
};

//添加用户表单的配置
const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 8,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 16,
        },
    },
};


//上传头像的方法
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    console.log(reader)
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
};

const UserTable = () => {
        //编辑用户
        const [editingUser, setEditingUser] = useState(false);
        const userFormRef = useRef()
        const [form] = Form.useForm();

        //用户表格数据
        const [userListData, setUserListData] = useState([])

        const [bordered, setBordered] = useState(false);
        const [size, setSize] = useState('表格尺寸');
        //展开操作
        const [expandable, setExpandable] = useState(defaultExpandable);
        const {Search} = Input;
        const {Option} = Select;
        //批量删除
        const [userSelectedRows, setUserSelectedRows] = useState([])
        const [userSelectedRowKeys, setUserSelectedRowKeys] = useState([])
        const [deleteModalText, setDeleteModalText] = useState('删除之后不可恢复!');
        const [deleteModalOpen, setDeleteModalOpen] = useState(false);
        const [userId, setUserId] = useState(null);

        //新增用户的拟态框
        const [modalOpen, setModalOpen] = useState(false);
        const [confirmLoading, setConfirmLoading] = useState(false);

        //上传头像
        const [loading, setLoading] = useState(false);
        const [imageUrl, setImageUrl] = useState([]);
        useEffect(() => {
            getUserListData()
        }, [])

        useEffect(() => {
            if (editingUser) {
                form.setFieldsValue({
                    user_avatar: imageUrl
                })
            }
        }, [imageUrl])

        //表格
        const columns = [
            {
                title: '用户头像',
                dataIndex: 'user_avatar',
                width: 100,
                render: cover => <Avatar size="large" src={cover}/>
            },
            {
                title: '用户昵称',
                dataIndex: 'nickname',
                width: 200
            },
            {
                title: '用户性别',
                dataIndex: 'gender',
                width: 200
            },
            {
                title: '手机号',
                dataIndex: 'phone',
                width: 200
            },
            {
                title: '密码',
                dataIndex: 'password',
                width: 200,
                render: text => <span>{text.replace(/./g, "*")}</span>
            },
            {
                title: '用户权限',
                dataIndex: 'role',
                width: 200
            },
            {
                title: '用户邮箱',
                dataIndex: 'user_email',
                width: 200,
            },
            {
                title: '操作',
                key: 'action',
                sorter: true,
                render: (_, record) => (
                    <Space size="middle">
                        <Tooltip title="修改">
                            <Button onClick={() => updateUser(record)} type="primary" style={{backgroundColor: '#ffa500'}}>
                                <EditOutlined/>
                            </Button>
                        </Tooltip>
                        <Tooltip title="删除">
                            <Button onClick={() => {
                                setUserId(record.id)
                                setDeleteModalOpen(true)
                            }} type="primary" danger>
                                <DeleteOutlined/>
                            </Button>
                        </Tooltip>
                    </Space>
                ),
            },
        ];


        //获取用户列表数据
        const getUserListData = async () => {
            const result = await reqGetUserList()
            setUserListData(result.data)
        }

        /*
        *       添加用户的事件
                添加用户表单
        *
        * */
        const addNewUser = () => {
            form.resetFields()
            setImageUrl(null)
            setEditingUser(false)
            setModalOpen(true)
        }
        //添加用户成功的事件
        const addAndUpdateHandleOk = async (fd) => {
            if (editingUser) {
                try {
                    const fd = form.getFieldValue()
                    setConfirmLoading(true);
                    const result = await reqUpdateUser({user_id: fd.id, fd})
                    if (result.status === 0) {
                        setTimeout(async () => {
                            setModalOpen(false);
                            setConfirmLoading(false);
                            message.success('修改用户成功')
                            getUserListData()
                        }, 1000);
                    } else {
                        setConfirmLoading(false)
                        message.error('修改失败')
                    }
                } catch (err) {
                    message.error(err)
                }
            } else {
                try {
                    setConfirmLoading(true);
                    const result = await reqAddUserList({...fd, user_avatar: fd.user_avatar[0]})
                    if (result.status === 0) {
                        setTimeout(async () => {
                            setModalOpen(false);
                            setConfirmLoading(false);
                            message.success('添加用户成功')
                            getUserListData()
                        }, 1000);
                    } else {
                        setConfirmLoading(false)
                        message.error('添加用户失败,手机号或昵称可能存在重复！')
                    }
                } catch (err) {
                    message.error(err)
                }
            }
        };
        const addHandleCancel = () => {
            setModalOpen(false);
        };

        //自定义上传
        const customRequest = async (options) => {
            // console.log(options)
            const {onSuccess, onError, file} = options;
            const fmData = new FormData()
            const config = {
                headers: {"content-type": "multipart/form-data"},
            };
            fmData.append("file", file);
            try {
                const res = await axios.post(
                    `${process.env.REACT_APP_API_URL}/admin/user-table/uploads`,
                    fmData,
                    config
                );
                const {url} = res.data;
                const fileObj = {
                    uid: res.data.id,
                    name: file.name,
                    status: "done",
                    url,
                };
                onSuccess(fileObj);
                console.log("server res: ", res);
            } catch (err) {
                console.log("Error: ", err);
                onError(err);
            }
        }
        //上传组件选择图片的事件
        const handleChange = (info) => {
            if (info.file.status === 'uploading') {
                setLoading(true);
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                console.log(info)
                getBase64(info.file.originFileObj, (url) => {
                    setLoading(false);
                    setImageUrl([url]);
                });
            }
        };
        const normFile = (e) => {
            if (Array.isArray(e)) {
                return e;
            }
            return e && e.fileList
        }
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined/> : <PlusOutlined/>}
                <div style={{marginTop: 8,}}></div>
            </div>
        )

//重置添加用户表单

        const reset = () => {
            userFormRef.current.resetFields()
        }


        //批量删除成功的操作
        const deleteOk = async () => {
            if (userId) {
                const result = await reqDeleteUser({user_id: userId})
                if (result.status === 0) {
                    setConfirmLoading(true);
                    setTimeout(() => {
                        setDeleteModalOpen(false);
                        setConfirmLoading(false);
                        getUserListData()
                        message.success('删除成功!')
                    }, 1000);
                } else {
                    setConfirmLoading(false)
                    message.error('删除失败!')
                }
            } else if (userSelectedRowKeys) {
                // console.log(1)
                const idList = []
                userSelectedRowKeys.forEach((id) => {
                    idList.push(id)
                })
                const result = await reqDeleteUserList(idList)
                if (result.status === 0) {
                    setConfirmLoading(true);
                    setTimeout(() => {
                        setDeleteModalOpen(false);
                        setConfirmLoading(false);
                        getUserListData()
                        message.success('删除成功')
                    }, 1000);
                }
            }


        }
        const deleteCancel = () => {
            setDeleteModalOpen(false)
        }

        //表格的选择框属性
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                setUserSelectedRows(selectedRows)
                setUserSelectedRowKeys(selectedRowKeys)
            },
            onSelect: (record, selected, selectedRows) => {
                setUserSelectedRows(selectedRows)
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                setUserSelectedRows(selectedRows)
            },
        };


        const tableColumns = columns.map((item) => ({
            ...item,
        }));
//表格可选配置
        const handleBorderChange = (enable) => {
            setBordered(enable);
        };
        const handleSizeChange = (e) => {
            setSize(e.target.value);
        };
        const handleExpandChange = (enable) => {
            setExpandable(enable ? defaultExpandable : undefined);
        };
        const tableProps = {
            bordered,
            size,
            expandable,
        }

        //更新用户
        const updateUser = (record) => {
            console.log(record)
            try {
                setEditingUser(true)
                setModalOpen(true)
                setImageUrl([record.user_avatar])
                if (form) {
                    form.setFieldsValue({
                        ...record,
                        user_avatar: imageUrl
                    })
                }
            } catch (err) {
                message.error(err)
            }
        }


//用户角色筛选
        const chooseUser = async (role) => {
            const result = await reqGetUserList()
            setUserListData(result.data.filter((item) => item.role.indexOf(role) !== -1))
        }

//重置表格
        const searchFormRef = useRef()
        const resetUserList = () => {
            getUserListData()
            searchFormRef.current.resetFields()
        }
        //搜索用户
        const searchUser = debounce(async (e) => {
            const result = await reqGetUserList()
            setUserListData(result.data.filter((item) => item.nickname.indexOf(e.target.value) !== -1))
        }, 500)


        //导出表格
        const exportTable = async () => {
            let _headers = [
                {k: 'nickname', v: '用户昵称'},
                {k: 'gender', v: '用户性别'},
                {k: 'phone', v: '手机号'},
                {k: 'role', v: '用户权限'},
                {k: 'user_email', v: '用户邮箱'},
            ]
            // if (userSelectedRows) {
            //     exportExcel(_headers, userSelectedRows)
            //     message.success('导出选中表格成功！')
            // }
            if (userSelectedRows.length === 0) {
                exportExcel(_headers, userListData)
                message.success('导出整个表格成功！')
            } else {
                exportExcel(_headers, userSelectedRows)
                message.success('导出选中表格成功！')
            }
        }


        //密码校验
        const validatePassword = (_, value) => {
            if (!value) {
                return Promise.reject('请输入密码!');
            }
            if (value.length < 6) {
                return Promise.reject('密码长度至少是6位!');
            }
            return Promise.resolve();
        };

        //确认密码校验
        const validateConfirmPassword = (_, value) => {
            if (!value) {
                return Promise.reject('请确认密码!');
            }
            if (value !== form.getFieldValue('password')) {
                return Promise.reject('两次密码输入必须一致!');
            }
            return Promise.resolve();
        };


        return (
            <div>
                <Card>
                    <div className={classes.HeaderHandles}>
                        <Space>
                            <Button type="primary" onClick={addNewUser}>新增用户</Button>
                            <Button type="primary" danger onClick={() => {
                                if (userSelectedRows.length !== 0) {
                                    setDeleteModalOpen(true)
                                } else {
                                    message.info('请勾选用户')
                                }
                            }}>批量删除</Button>
                            <Button onClick={exportTable}>
                                <DownloadOutlined/>导出
                            </Button>
                        </Space>
                        <Form ref={searchFormRef}>
                            <Space>
                                <Form.Item name="selectRole">
                                    <Select
                                        onChange={chooseUser}
                                        placeholder="用户角色筛选"
                                        style={{width: 160}}
                                        options={[
                                            {
                                                value: '月度会员',
                                                label: '月度会员',
                                            },
                                            {
                                                value: '季度会员',
                                                label: '季度会员',
                                            },
                                            {
                                                value: '年度会员',
                                                label: '年度会员',
                                            },
                                            {
                                                value: '普通用户',
                                                label: '普通用户',
                                            },
                                        ]}
                                    />
                                </Form.Item>
                                <Form.Item name="searchUser">
                                    <Search onChange={searchUser} style={{width: 300}} placeholder="根据昵称搜索用户"
                                            allowClear
                                            enterButton/>
                                </Form.Item>
                                <Form.Item>
                                    <Button type="primary" onClick={resetUserList}>重置</Button>
                                </Form.Item>
                            </Space>
                        </Form>
                    </div>
                    <Card style={{marginTop: 10}}>
                        <Form
                            layout="inline"
                            style={{
                                marginBottom: 16,
                            }}
                        >
                            <Form.Item label="边框">
                                <Switch checked={bordered} onChange={handleBorderChange}/>
                            </Form.Item>
                            <Form.Item label="展开">
                                <Switch checked={!!expandable} onChange={handleExpandChange}/>
                            </Form.Item>
                            <Form.Item label="表格尺寸">
                                <Radio.Group value={size} onChange={handleSizeChange}>
                                    <Radio.Button value="large">大</Radio.Button>
                                    <Radio.Button value="middle">中</Radio.Button>
                                    <Radio.Button value="small">小</Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                        </Form>
                        <Table
                            {...tableProps}
                            dataSource={userListData}
                            columns={tableColumns}
                            rowSelection={{
                                ...rowSelection,
                            }}
                            rowKey={record => record.id}
                        />
                    </Card>
                    <Modal
                        width={800}
                        title={editingUser ? "编辑用户" : "新增用户"}
                        open={modalOpen}
                        onCancel={addHandleCancel}
                        footer={null}
                    >
                        <Form
                            {...formItemLayout}
                            ref={userFormRef}
                            form={form}
                            name="add"
                            onFinish={addAndUpdateHandleOk}
                            style={{maxWidth: 600}}
                            scrollToFirstError
                        >
                            <Form.Item
                                name="phone"
                                label="手机号"
                                rules={[
                                    {
                                        type: 'phone',
                                        message: '手机号不符合规范!',
                                    },
                                    {
                                        required: true,
                                        message: '请输入手机号!',
                                    },
                                ]}
                            >
                                <Input maxLength={13}/>
                            </Form.Item>

                            <Form.Item
                                name="password"
                                label="密码"
                                rules={[{validator: validatePassword}]}
                                hasFeedback
                            >
                                <Input.Password/>
                            </Form.Item>

                            {
                                editingUser ? null :
                                    <Form.Item
                                        name="confirm"
                                        label="确认密码"
                                        dependencies={['password']}
                                        hasFeedback
                                        rules={[{validator: validateConfirmPassword}]}
                                    >
                                        <Input.Password/>
                                    </Form.Item>
                            }


                            <Form.Item
                                name="nickname"
                                label="昵称"
                                tooltip="你期望取一个什么昵称?"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入昵称!',
                                        whitespace: true,
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="user_email"
                                label="邮箱"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入邮箱!',
                                        whitespace: true,
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="gender"
                                label="性别"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择性别!',
                                    },
                                ]}
                            >
                                <Select placeholder="选择性别">
                                    <Option value="男">男</Option>
                                    <Option value="女">女</Option>
                                </Select>
                            </Form.Item>

                            <Form.Item
                                name="user_avatar"
                                label="上传头像"
                                rules={[
                                    {
                                        required: true,
                                        message: '请上传头像!',
                                    },
                                ]}
                                getValueFromEvent={normFile}
                                valuePropName="fileList">

                                <Upload
                                    listType="picture-card"
                                    showUploadList={false}
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                    maxCount={1}
                                    customRequest={customRequest}
                                >
                                    {imageUrl ? (
                                        <img
                                            src={imageUrl}
                                            alt="avatar"
                                            style={{width: '100%'}}
                                        />
                                    ) : (uploadButton)}
                                </Upload>
                            </Form.Item>

                            <Form.Item
                                name="role"
                                label="分配权限"
                                rules={[
                                    {
                                        required: true,
                                        message: '请分配权限性别!',
                                    },
                                ]}
                            >
                                <Select placeholder="分配该用户权限">
                                    <Option value="月度会员">月度会员</Option>
                                    <Option value="季度会员">季度会员</Option>
                                    <Option value="年度会员">年度会员</Option>
                                    <Option value="普通用户">普通用户</Option>
                                </Select>
                            </Form.Item>

                            <div className={classes.FooterBtn}>
                                <div>
                                    <Form.Item>
                                        <Button onClick={reset} type="primary">
                                            重置表单
                                        </Button>
                                    </Form.Item>
                                </div>
                                <div style={{display: 'flex'}}>
                                    <Space>
                                        <Form.Item>
                                            <Button onClick={() => {
                                                setConfirmLoading(false)
                                                setModalOpen(false)
                                            }}>
                                                取消
                                            </Button>
                                        </Form.Item>
                                        <Form.Item>
                                            <Button type="primary" htmlType="submit" loading={confirmLoading}>
                                                {editingUser ? "确认修改" : "确认添加"}
                                            </Button>
                                        </Form.Item>
                                    </Space>
                                </div>
                            </div>
                        </Form>
                    </Modal>
                </Card>
                <Modal
                    centered
                    title="确定要删除所选项吗？"
                    open={deleteModalOpen}
                    onOk={deleteOk}
                    confirmLoading={confirmLoading}
                    onCancel={deleteCancel}
                    okText="确认删除"
                    cancelText="取消"
                >
                    <p>{deleteModalText}</p>
                </Modal>
            </div>
        )
    }
;

export default UserTable;